<?php
/**
 * Created By Project
 * Author: 陈东
 * Copyright：陈东
 * Source Code：陈东
 * Explain：I shall not authorize for any other commercial purposes, law breakers must be prosecuted.
 */
namespace Admin\Controller;
use Think\Controller;

class BatchController extends BaseController {

    public function index(){
		
    	$domainid = I('get.domainid');
    	$rootid   = I('get.rootid');
    	$pici 	  = I('get.batchnumber');
    	$this->assign('domainid',$domainid);
    	$this->assign('rootid',$rootid);    	
    	
    	//获取生产批次
    	$batch_result_tmp = $this->get_batchnumber($rootid);
    	$batch_result = $batch_result_tmp[0]['batchnumber'] ? $batch_result_tmp[0]['batchnumber'] : 0;
    	$this->assign('batch_result_count', $batch_result);
    	$this->assign('batch_result', $batch_result_tmp);

    	$pici = !empty($pici) ? $pici : $batch_result;
    	$this->assign('pi_ci', $pici);
    	$get_code_validation = $this->get_code($pici, $rootid);	//获取批量华人码信息
		if($get_code_validation == 'no') $this->assign('code_val', $get_code_validation);
		$this->assign('marules', $this->getmarules());
		$this->assign('rulesid', $this->getrulestoma($rootid));
		$this->assign('rulesarray', $this->getrulesarraytoma($this->getrulestoma($rootid)['isrules']));
		$this->assign('rulesarray_awardkind', $this->get_pos_award($this->getrulestoma($rootid)['isrules']));
		$this->get_sell_num($rootid); //实际卖出多少（扫了多少产品）
		$this->get_sma_num($rootid); //总扫码次数
    	$this->display();
    }
    
    /**
     * 获取当前码的奖品类型
     */
    protected function get_pos_award($typeid){
    	$award = D(C('TABLE_AWARD'));
    	$res = $award->distinct(true)->field('awardkind')->where(array('typeid'=>$typeid))->select();
    	return $res;
    }
    
    /**
     * 获取批次
     */
	protected function get_batchnumber($rootid = null){
		if(empty($rootid)) return null;
		$field = 'batchnumber';
		$randnumber = D(C('TABLE_RANDNUMBER'));
		$res = $randnumber->distinct(true)->field($field)->order($field.' desc')->where(array('ma_rootid' => $rootid))->select();
		return $res;
	}
	
	/**
	 * 删除生产过的码
	 */
	public function ma_delete(){
		$rootid   = I('get.rootid');
		$pici 	  = I('get.batchnumber');
		if($pici != '' && $pici != 0) $where['batchnumber']	= $pici;
		$where['ma_rootid']	= $rootid;
		$randnumber = D(C('TABLE_RANDNUMBER'));
		$res = $randnumber->where(array('ma_rootid' => $rootid, 'batchnumber' => $pici))->delete();
		$res ? $this->success('删除成功！') : $this->error('删除失败！','',1);
	}
    
	/**
	 * 获取当前码的规则ID号
	 */
	public function getrulestoma($rootid){
		$type = D(C('TABLE_TYPE'));
		$res = $type->find($rootid);
		return $res;
	}

	/**
	 * 获取当前码的规则
	 */
	protected function getrulesarraytoma($typeid){
		$award = D(C('TABLE_AWARD'));
		$res = $award->where(array('typeid'=>$typeid))->select();
		return $res;
	}

	/**
	 * 获取一物一码游戏规则
	 */
	protected function getmarules(){
		$award = D(C('TABLE_AWARD'));
		$res   = $award->where(array('typeid'=>0,'userid'=>session('userinfo')['id']))->select();
		return $res;
	}

	/**
	 * 开始批量生产华人码
	 */
    public function getqrcodelist(){
		$rulesid = I('post.rulesid');
		if(!is_numeric($rulesid)){
			echo -2; //奖品规则非法
			die;
		}
		$total 		= 1000;					//每次提交多少数据
    	$domainid 	= I('post.domainid');
    	$rootid 	= I('post.rootid');
    	$make 		= I('post.make');
    	$m_num 		= I('post.m_num');		//生产数量
    	$batchnumber= I('post.pici')+1;		//生产批次+1
    	$befr_url 	= C('WEBDOMAIN');		//域名地址
    	if($m_num < $total) $total = $m_num;
    	//数量判断
    	if($m_num < 1){
    		$this->error('生产数量不能为空！','',2);
    		exit();
    	}
    	//开始生产
    	if($make == 1){
			$folder = '/codeimgs/'.date("Ymd").$rootid;
			$rand   = D(C('TABLE_RANDNUMBER'));
			$dataList = array();
			for($i = 1; $i <= $m_num; $i++){
				//获取随机唯一标示
				//$randcode = uniqid($rootid.$i);
				$randcode = $rootid.$i.substr(md5(uniqid($rootid.$i)),8,10);
				//拼接生产华人码图片的地址
				//$code_url = $befr_url.'/?'.$randcode;
				$ma_randcodeimgurl = $befr_url.$folder.'/'.$randcode.'.png';
				$dataList[] = array(
					'ma_rootid'				=> $rootid,
					'ma_domainid'			=> $domainid,
					'ma_randnumber'			=> $randcode,
					'ma_randcodeimgurl'		=> $ma_randcodeimgurl,
					'ma_randnumber_state'	=> 1,
					'ma_randnumber_date'	=> date("Y-m-d H:i:m"),
					'batchnumber'			=> $batchnumber
				);
				if($i % $total == 0){
					$rand->addAll($dataList);
					$dataList = null;
				}
			}
			//给当前码插入规则
			$this->saveruletoma($rootid, $rulesid);
			echo 1;
    	}
    }
	protected function saveruletoma($rootid, $rulesid){
		$type = M(C('TABLE_TYPE'));
		$data['isrules'] = $rulesid;
		$res = $type->where(array('id' => $rootid))->save($data);
		if($res || $res==0){
			return true;
		}else{
			return false;
		}
	}
	public function chauxn(){
		$id = I('get.id');
		$rand = M(C('TABLE_RANDNUMBER'));
		$res = $rand->where(array('ma_rootid'=>92,'ma_type'=>$id))->count();
		echo $res;
	}

	public function allotaward(){
		$rulesid 	 = I('post.rulesid');
		$rootid  	 = I('post.rootid');
		$batchnumber = I('post.pici')+1;		//生产批次+1
		$rules   = $this->getrules($rulesid);
		foreach($rules as $v){
			if($v['awardnum'] > 0) $this->randchangevalue($rootid, $v['awardnum'], $v['id'], $batchnumber);
		}
		echo 1;
	}

	/**
	 * 随机改变指定数量的字段值
	 */
	protected function randchangevalue($rootid, $num, $value, $batchnumber){
		$rand    = M(C('TABLE_RANDNUMBER'));
		$idarray = null;
		//$res = $rand->field('id')->where("ma_rootid=$rootid and ma_type=1 and id>1178401")->order('rand()')->limit($num)->select();
		$res = $rand->field('id')->where(array('ma_rootid' => $rootid, 'ma_type' => 1, 'batchnumber' => $batchnumber))->order('rand()')->limit($num)->select();
		if($res){
			foreach ($res as $v) $id .= $v['id'].',';
			$id = rtrim($id,',');
		}
		$this->randsavedata($id, $value);
	}
	protected function randsavedata($id, $value){
		$rand = D(C('TABLE_RANDNUMBER'));
		$map['id'] = array('in',$id);
		$res = $rand->where($map)->save(array('ma_type' => $value));
		return $res ? true : false;
	}

	/**
	 * 取出规则中的定义
	 */
	protected function getrules($id){
		$award = A('Award');
		return $award->getaward($id);
	}

	/**
	 * 批量执行生产
	 */
	protected function production($befr_url,$rootid,$domainid){
		//获取随机唯一标示
		$randcode 			= uniqid();
		//拼接生产华人码的地址
		$code_url 			= $befr_url.'/?'.$randcode;
		//执行华人码生产逻辑
		$folder   			= '/codeimgs/'.date("Ymd").$rootid;
		$ma_randcodeimgurl 	= $befr_url.$folder.'/'.$randcode.'.png';
		//执行插入数据
		if(!$this->insertrandcode($rootid, $domainid, $randcode, $ma_randcodeimgurl)){
			return false;
		}else{
			//$this->getmaode($randcode,$code_url,$rootid);
		}
	}
    
    /**
     * 生产华人码逻辑
     */
    protected function getmaode($randcode,$url,$rootid){
		$datefolder 	= date("Ymd").$rootid;
		$folder 		= './codeimgs/'.$datefolder;
		if (!file_exists($folder)){
			mkdir($folder,'0777');
		}
		$path = ltrim($folder,'./').'/'.$randcode.'.png';
		$this->qrcodes($path,$url);
    }
    
    /**
     * 插入随机码
     */
    protected function insertrandcode($ma_rootid,$ma_domainid,$ma_randnumber,$ma_randcodeimgurl){
    	$rand = D(C('TABLE_RANDNUMBER'));
    	$rand->ma_rootid 			= $ma_rootid;
    	$rand->ma_domainid 			= $ma_domainid;
    	$rand->ma_randnumber 		= $ma_randnumber;
    	$rand->ma_randcodeimgurl 	= $ma_randcodeimgurl;
    	$rand->ma_randnumber_state 	= 1;
    	$rand->ma_randnumber_date 	= date("Y-m-d H:i:m");
    	$result = $rand->add();
    	if($result){
    		return true;
    	}else{
    		return false;
    	}
    }

	/**
	 * 获取实际卖出多少
	 */
	protected function get_sell_num($rootid){
		$where['ma_rootid']   = $rootid;
		$where['ma_hb_cishu'] = 1;
		$rand  = D(C('TABLE_RANDNUMBER'));
		$count = $rand->where($where)->count();
		//echo $count;
		$this->assign('sell_num',$count);
	}

	/**
	 * 总扫码次数
	 */
	protected function get_sma_num($rootid){
		$where['id'] = $rootid;
		$rand = D(C('TABLE_TYPE'));
		$res  = $rand->where($where)->find();
		$num  = 0;
		if($res) $num = $res['num'];
		$this->assign('sma_num',$num);
	}
    
    /**
     * 获取批量华人码信息
     */
    protected function get_code($batch_result, $maid=null){
		if(!empty($maid)){
			$where['ma_rootid'] = $maid;
			$where['isvalid']   = array('neq',0);
			if($batch_result) $where['batchnumber'] = $batch_result;
		}else{
			$where = null;
		}
    	$rand  = D(C('TABLE_RANDNUMBER'));
    	$count = $rand->where($where)->count();
    	//每页显示条数
    	$num   = C('MAIN_NUM');
    	$page  = new \Think\Page($count,$num);
    	$obj   = pagestyle($page);
    	$show  = $obj->show();
    	$result= $rand->where($where)->order("zjtime DESC,ma_hb_cishu DESC")->limit($obj->firstRow.','.$obj->listRows)->select();
		if($result){
			$this->assign('randlist',$result);
			$this->assign('page',$show);
		}else{
			return 'no';
		}
    }

	/**
	 * 删除当前码
	 */
	public function madelete(){
		$id 	= I('get.id');
		$rootid = I('get.rootid');
		$randma = D(C('TABLE_RANDNUMBER'));
		$res 	= $randma->delete($id);
		$res ? $this->success('删除成功！') : $this->error('删除失败！','',1);
	}

	/**
	 * 设定实物
	 */
	public function setaward(){
		$id 		= I('get.id');
		$matype 	= I('get.matype');
		$randnumber = D(C('TABLE_RANDNUMBER'));
		$data['ma_type'] = $matype;
		$res = $randnumber->where(array('id'=>$id))->save($data);
		$res ? $this->success('设定完毕！') : $this->error('设定失败！','',1);
	}

	public function batchqrcodes(){
		$rootid = I('get.rootid');
		$pici 	= I('get.batchnumber');
		$datefolder = date("Ymd").$rootid;
		$folder = './codeimgs/'.$datefolder;
		if (!file_exists($folder)) mkdir($folder,'0777');
		$folderpath = ltrim($folder,'./');

		$randma = D(C('TABLE_RANDNUMBER'));
		if($pici != '' && $pici !=0) $where['batchnumber'] = $pici;
		$where['ma_rootid'] = $rootid;
		$res = $randma->field('ma_rootid,ma_randnumber')->where(array('ma_rootid'=>$rootid))->order('id asc')->select();
		if($res){
			foreach($res as $v){
				$marandnumber = $v['ma_randnumber'];
				$path = $folderpath.'/'.$marandnumber.'.png';
				$url = C('WEBDOMAIN').'/?'.$marandnumber;
				$this->qrcodes($path,$url);
			}
			$this->filetozip($folderpath);
		}
	}

	/**
	 * 打包生成ZIP格式并下载
	 */
	protected function filetozip($cur_file){
		import('ORG.Util.FileToZip');
		$handler = opendir($cur_file);    //$cur_file 文件所在目录
		$download_file = array();
		$i = 0;
		while( ($filename = readdir($handler)) !== false ) {
			if($filename != '.' && $filename != '..') {
				$download_file[$i++] = $filename;
			}
		}
		closedir($handler);
		$scandir=new \traverseDir($cur_file,$cur_file);    //$save_path zip包文件目录
		$scandir->tozip($download_file);
	}

	/**
	 * 查询奖品是被谁领取
	 */
	public function lookuserinfo(){
		$result = null;
		$randcode = I('post.randcode');
		$vrootid = I('post.vrootid');
		$awartype = I('post.awartype');
		$result = $this->browershiwu($randcode,$vrootid,$awartype);
		if($result){
			if($randcode!='000000'){
				echo $result;
			}else{
				$result1 = $this->browerhb($randcode,$vrootid);
				$result .= $result1;
				echo $result;
			}
		}
	}

	/**
	 * 查询领取实物奖品的记录
	 */
	protected function browershiwu($randcode,$vrootid){
		$result = null;
		$telinfo = D(C('TABLE_TELINFO'));
		if($randcode!='000000'){
			$res = $telinfo->where(array('ma_randinfo'=>$randcode))->select();
		}else{
			$res = $telinfo->table('hrma_randnumber rand,hrma_telinfo telinfo')->where("(rand.ma_randnumber = telinfo.ma_randinfo) and (rand.ma_rootid=$vrootid)")->select();
		}
		if($res){
				foreach($res as $v){
					$result .="<tr class=\"tr-line\">"
							. "				<td>".$v['ma_randinfo']."</td>"
							. "				<td style=\"text-align:left; padding-left:6px;\">".$this->randnumbertotitle($v['ma_randinfo'])."</td>"
							. "				<td>".$v['username']."</td>"
							. "				<td>".$v['tel']."</td>"
							. "				<td style=\"text-align:left; padding-left:6px;\">".$v['address']."</td>"
							. "				<td>".$this->openidtoinfo($v['useropenid'],'nickname')."</td>"
							. "				<td>".$this->issex($v['useropenid'])."</td>"
							. "				<td>".$this->randnumbertozjtime($v['ma_randinfo'],'zjtime')."</td>"
							. "			</tr>"
							. "<tr class=\"tr-line\">"
							. "				<td></td>"
							. "				<td></td>"
							. "				<td style=\"background-color:#00a1aa; color:#fff;\" colspan=\"6\">".$this->randnumbertoawarname($v['ma_randinfo'])."</td>"
							. "			</tr>"
							."";
				}
		}
		return $result;
	}

	/**
	 * 查询领取红包的记录
	 */
	protected function browerhb($randcode,$vrootid){
			$result = null;
			$randnumberhb = D(C('TABLE_RANDNUMBERHB'));
			if($randcode!='000000'){
				$reshb = $randnumberhb->where(array('ma_randnumber'=>$randcode))->select();
			}else{
				$reshb = $randnumberhb->table('hrma_randnumber rand,hrma_randnumber_hb hb')->where("(rand.ma_randnumber = hb.ma_randnumber) and (rand.ma_rootid=$vrootid)")->select();
			}
			if($reshb){
				foreach($reshb as $v){
					$result .="<tr class=\"tr-line\">"
							. "				<td>".$v['ma_randnumber']."</td>"
							. "				<td style=\"text-align:left; padding-left:6px;\">".$this->randnumbertotitle($v['ma_randnumber'])."</td>"
							. "				<td></td>"
							. "				<td></td>"
							. "				<td style=\"text-align:left; padding-left:6px;\"></td>"
							. "				<td>".$this->openidtoinfo($v['ma_user_openid'],'nickname')."</td>"
							. "				<td>".$this->issex($v['ma_user_openid'])."</td>"
							. "				<td>".$this->randnumbertozjtime($v['ma_randnumber'],'zjtime')."</td>"
							. "			</tr>"
							. "<tr class=\"tr-line\">"
							. "				<td></td>"
							. "				<td></td>"
							. "				<td style=\"background-color:#00a1aa; color:#fff;\" colspan=\"5\">领取红包金额： ".$v['ma_money']." 元</td>"
							. "				<td style=\"background-color:#00a1aa; color:#fff;\">领取状态：".$this->lqstatus($v['ma_mch_billno'])."</td>"
							. "			</tr>"
							."";
				}
			}
			return $result;
	}

	/**
	 * 判断红包是否被领取还是被退回
	 */
	public function lqstatus($ma_mch_billno){
		$confirm = md5($ma_mch_billno.'cf@huaren888');
		$getmoenystateurl = "http://pay.hrtv.cn/hongbao/gethbinfo?mch_billno=".$ma_mch_billno."&appid=wx30934416968cbcb7&confirm=".$confirm;
		$jsonresult = file_get_contents($getmoenystateurl);
		$jsonresult = trim($jsonresult, "\xEF\xBB\xBF");
		$jsonresult = json_decode($jsonresult,true);
		/*如果已领取*/
		$m_status = trim($jsonresult['status']);
		switch ($m_status){
			case 'RECEIVED':
				return '已领取';
				break;
			case 'REFUND':
				return '已退款';
				break;
			case 'SENT':
				return '已发放待领取';
				break;
			case 'RFUND_ING':
				return '退款中';
				break;
			case 'FAILED':
				return '发放失败';
				break;
			case 'SENDING':
				return '发放中';
				break;
			default:
				return 'error';
		}
	}

	/**
	 * 判断是男是女
	 */
	public function issex($useropenid){
		$sex = $this->openidtoinfo($useropenid,'sex');
		if($sex==1){
			$sexs = '男';
		}else if($sex==0){
			$sexs = '女';
		}else{
			$sexs = '-';
		}
		return $sexs;
	}

	/**
	 * 根据微信openid获取昵称，男女
	 */
	public function openidtoinfo($openid,$field){
		$r = request_get(C('APIADDRES1')."/getuserinfo?token=".$openid);
		return $r['data'][$field];
	}

	/**
	 * 根据marandnumber获取码台标题
	 */
	public function randnumbertotitle($randcode){
		$type = D(C('TABLE_TYPE'));
		$r = $type->field('typename')->where(array('id'=>$this->randnumbertozjtime($randcode,'ma_rootid')))->find();
		if($r){
			return $r['typename'];
		}
	}

	/**
	 * 根据marandnumber获取中奖时间
	 */
	public function randnumbertozjtime($randcode,$field){
		$randnumber = D(C('TABLE_RANDNUMBER'));
		$res = $randnumber->where(array('ma_randnumber'=>$randcode))->find();
		if($res){
			return $res[$field];
		}
	}

	/**
	 * 根据marandnumber获取奖品名称
	 */
	public function randnumbertoawarname($randcode){
		$award = D(C('TABLE_AWARD'));
		$r = $award->field('awardname')->where(array('id'=>$this->randnumbertozjtime($randcode,'ma_type')))->find();
		if($r){
			return $r['awardname'];
		}
	}

	public function exportdata(){
		$rootid  = I('get.rootid');
		$awardid = I('get.awardid');
		$pici 	 = I('get.batchnumber');
		if($pici == '' || $pici == 0){
			$where = "ma_rootid = $rootid and ma_type = $awardid";
		}else{
			$where = "ma_rootid = $rootid and ma_type = $awardid and batchnumber = $pici";
		}
		$rand = D(C('TABLE_RANDNUMBER'));
		$res  = $rand->field('ma_randnumber')->where($where)->select();
		//$res  = $rand->field('ma_randnumber')->where("ma_rootid=$rootid and ma_type=$awardid and id>1178401")->select();
		if($res){
			$i = 1;
			foreach($res as &$v){
				//$v['id'] = $i;
				$v['link'] = C('WEBDOMAIN').'/?'.$v['ma_randnumber'];
				unset($v['ma_randnumber']);
				$i++;
			}
			exportexcel($res,array('link'),date("Ymd").$rootid);
			//exportexcel($res,array('id','link'),date("Ymd").$rootid);
		}
	}

}